﻿Shader "Running/terrainNormalDepth"
{
	Properties
	{
		nearDepth("nearDepth", Float) = 0
		farDepth("farDepth", Float) = 1
	}
		
	SubShader
	{
		Tags { 
			"RenderType" = "Opaque" 
			"NormalDepthRender" = "Terrain"
		}
		LOD 100
		Pass {

			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag
			#include "UnityCG.cginc"

			struct appdata
			{
				float4 vertex : POSITION;
				float3 normal : NORMAL;
			};

			struct v2f
			{
				float4 vertex : SV_POSITION;
				float4 oNormalDepth : TEXCOORD0;
			};
			v2f vert(appdata v)
			{
				v2f o;
				float4 pos = mul(UNITY_MATRIX_MVP, v.vertex);
				o.vertex = pos;
				/*
				float4x4 mv = UNITY_MATRIX_MV;
				float3x3 mv1;
				float4 row0 = mv[0];
				float4 row1 = mv[1];
				float4 row2 = mv[2];
				mv1[0] = row0.xyz;
				mv1[1] = row1.xyz;
				mv1[2] = row2.xyz;
				//透视镜头w 有作用  平视镜头 w =1   pos.w 所以
				o.oNormalDepth.xyz = mul(mv1, v.normal.xyz);
				*/
				//o.oNormalDepth.xyz = mul((float3x3)(UNITY_MATRIX_IT_MV), v.normal.xyz);
				//o.oNormalDepth.xyz = mul(UNITY_MATRIX_IT_MV, v.normal).xyz;
				//o.oNormalDepth.xyz = mul((float3x3)(UNITY_MATRIX_MV), v.normal.xyz);

				o.oNormalDepth.xyz = normalize(mul((float3x3)UNITY_MATRIX_IT_MV, v.normal));


				o.oNormalDepth.w = pos.z;
				return o;
			}

			uniform float nearDepth;
			uniform float farDepth;

			fixed4 frag(v2f i) : SV_Target
			{
				//-1 ,1 到 0 - 1 
				float4 col;
				
				//col.r = (i.oNormalDepth.x + 1.0) * 0.5;
				
				col.r = (i.oNormalDepth.x+1) * 0.5;

				col.g = (i.oNormalDepth.y + 1.0) * 0.5;
				col.b = (i.oNormalDepth.z + 1.0) * 0.5;
				//col.g = col.r;
				//col.b = col.r;

			//col.rgb = i.oNormalDepth.xyz;
				
				//depth camera depth 转化为 0 1 范围
				float4 normalDepth = i.oNormalDepth;
				normalDepth.w = saturate((i.oNormalDepth.w-nearDepth) / (farDepth-nearDepth));
				//normalDepth.w = i.oNormalDepth.w;
				
				/*
				col.r = normalDepth.w;
				col.g = normalDepth.w;
				col.b = normalDepth.w;
				*/

				col.a = normalDepth.w;
				return col;
			}
			ENDCG
		}

	}
}
